package com.ujson.chat.client.handler;

import com.ujson.base.common.utils.LogUtil;
import com.ujson.chat.client.controller.CommandController;
import com.ujson.chat.client.session.ClientSession;
import com.ujson.chat.common.handler.AbstractHandler;
import com.ujson.chat.common.proto.MessageProto;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <h3>ujson-parent</h3>
 * <p>登录响应处理器</p>
 *
 * @author JerryLiu  a1031757312@gmail.com
 * @version 1.0
 * @date 2021-11-24 21:55
 */
@Slf4j
@Service
@ChannelHandler.Sharable
public class LoginResponseHandler extends AbstractHandler {
    @Autowired
    private HeartbeatResponseHandler heartbeatResponseHandler;
    @Autowired
    private CommandController commandController;

    @Override
    public MessageProto.MessageType getMessageType() {
        return MessageProto.MessageType.LOGIN_RESPONSE;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        if (!super.messageTypeCheck(ctx, msg)) {
            return ;
        }
        // startt business handle
        LogUtil.info(log, "login response read");

        MessageProto.Message message = (MessageProto.Message) msg;
        MessageProto.LoginResponse loginResponse = message.getLoginResponse();
        Channel channel = ctx.channel();
        if (loginResponse.getResult()) {
            LogUtil.info(log, "login success. session: " + loginResponse.getSessionId());

            // 登录成功, 将用户与channel关联, 删除loginResponseHandler, 添加heartbeatHandler
            ClientSession.getClientSession(channel).loginSuccess(ctx, loginResponse.getSessionId());
            channel.pipeline().addAfter("encoder", "beartbeat", heartbeatResponseHandler);
            channel.pipeline().remove(this);
            // 激活心跳
            heartbeatResponseHandler.channelActive(ctx);
        } else {
            LogUtil.info(log, "login error.");
        }
        ClientSession.getClientSession(channel).notifyLogin();
    }

}
